package com.xhorse.lockplatform.comm.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @author Think
 * @date 2017/11/07
 */
@Aspect
@Component
public class LogAspect {

    private final static Logger logger = LoggerFactory.getLogger(LogAspect.class);

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(public * com.xhorse.lockplatform..*Controller.*(..))")
    public void log() {
    }

    @Before("log()")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        startTime.set(System.currentTimeMillis());
        HttpServletRequest request = requestAttributes.getRequest();
        logger.info("url = {}", request.getRequestURL());
        logger.info("http_method = {}", request.getMethod());
        logger.info("ip = {}", request.getRemoteAddr());
        logger.info("class_method = {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint
                .getSignature().getName());
        logger.info("args = {}", joinPoint.getArgs());
    }

    @After("log()")
    public void after() {
    }

    @AfterReturning(returning = "respData", pointcut = "log()")
    public void doAfterResponse(Object respData) {
        String returnInfo;
        if (null != respData && respData.getClass().isAssignableFrom(ResponseEntity.class)) {
            returnInfo = "ResponseEntity";
        } else {
            // 出参就不再格式化输出了，因为通常接口返回的都是实体类，类属性很多，很占面积，影响查日志
            returnInfo = JSON.toJSONStringWithDateFormat(respData, JSON.DEFFAULT_DATE_FORMAT, SerializerFeature
                    .WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature
                    .WriteNullNumberAsZero, SerializerFeature.WriteNullListAsEmpty, SerializerFeature
                    .WriteNullBooleanAsFalse);
        }
        logger.info("response={}", returnInfo);
        logger.info("spend time : " + (System.currentTimeMillis() - startTime.get()));
    }
}
